package com.briup.bookstore.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.briup.bookstore.common.constant.OrderConstant;
import com.briup.bookstore.common.exception.ServiceException;
import com.briup.bookstore.common.response.ResultCode;
import com.briup.bookstore.common.security.SecurityContext;
import com.briup.bookstore.domain.bean.Order;
import com.briup.bookstore.domain.dto.OrderPayDTO;
import com.briup.bookstore.domain.dto.OrderPaySuccessDTO;
import com.briup.bookstore.domain.vo.OrderDetailVO;
import com.briup.bookstore.domain.vo.OrderVO;
import com.briup.bookstore.mapper.OrderMapper;
import com.briup.bookstore.service.OrderPayService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class OrderPayServiceImpl implements OrderPayService {

    private final AlipayClient alipayClient;
    private final OrderMapper orderMapper;

    @Override
    public String pay(OrderPayDTO payDTO) {
        // 校验订单是否存在以及是否为待支付状态
        OrderVO orderVO = checkOrderExist(payDTO.getOrderId());

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        AlipayTradePayModel model = new AlipayTradePayModel();
        // 设置参数
        model.setOutTradeNo(payDTO.getOrderId());
        // 订单金额
        model.setTotalAmount(payDTO.getTotalPrice().toString());
        // 订单标题
        model.setSubject("订单支付");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        // 将参数注入到请求中
        request.setBizModel(model);
        // 设置回调地址
        request.setReturnUrl(payDTO.getPathUrl());

        // 生成对应的页面sdk
        String result = "";
        try {
            result = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            throw new ServiceException(ResultCode.ALIPAY_PAY_ERROR);
        }

        return result;
    }

    @Override
    public void paySuccess(OrderPaySuccessDTO paySuccessDTO) {
        // 校验订单是否存在以及是否为待支付状态
        OrderVO orderVO = checkOrderExist(paySuccessDTO.getOrderId());
        // 更新订单数据
        Order order = Order.builder()
                .id(orderVO.getOrderId())
                .status(OrderConstant.PAID_UNSHIPPED.getStatus())
                .payDate(paySuccessDTO.getPayDate())
                .payWay(paySuccessDTO.getPayWay())
                .build();
        // 更新订单数据库
        orderMapper.updateById(order);
    }


    private OrderVO checkOrderExist(String orderId) {
        // 查询订单是否存在
        OrderDetailVO orderVO = orderMapper.queryDetailById(SecurityContext.userId(), orderId);
        if (orderVO == null) {
            throw new ServiceException(ResultCode.ORDER_NOT_EXIST);
        }
        // 校验订单状态是否为待支付
        if (orderVO.getStatus() != OrderConstant.CREATED_UNPAID.getStatus()) {
            throw new ServiceException(ResultCode.ORDER_STATUS_ERROR);
        }
        return orderVO;
    }
}
